package com.health.viewscontrols.medical.device.ah;

import android.bluetooth.BluetoothGatt;
import android.os.Handler;
import android.util.Log;

import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleIndicateCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.utils.HexUtil;
import com.health.viewscontrols.medical.base.BaseDeviceActivity;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.views.twj.TwjConstans;

import java.text.DecimalFormat;
import java.util.List;
import java.util.UUID;

/**
 * 脉搏波体温计4.0
 */
public class AHF701Activity extends BaseDeviceActivity {

    public final static UUID UUID_SERVICE = UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");
    public final static UUID UUID_NOTIFY = UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb");

    private BleDevice fastBleDevice;

    @Override
    public void doBusiness() {
        tv_operation_tips.setText(com.nova.health.ble.R.string.ah_YUYUE1);
        BleManager.getInstance().init(getApplication());
        BleManager.getInstance()
                .enableLog(true)
                .setReConnectCount(1, 30000)
                .setConnectOverTime(30000)
                .setOperateTimeout(30000);

        startDevice();
    }

    @Override
    public void startDevice() {
        if (fastBleDevice == null) {
            showProgressDialog("正在连接" + deviceEnum.getTitle());
            BleManager.getInstance().scan(new BleScanCallback() {
                @Override
                public void onScanStarted(boolean success) {
                }

                @Override
                public void onLeScan(BleDevice bleDevice) {
                    super.onLeScan(bleDevice);
                }

                @Override
                public void onScanning(BleDevice bleDevice) {
                    Log.e(TAG, "onScanning: " + bleDevice.getName() + "  " + bleDevice.getMac() );
                    if (bleDevice != null && bleDevice.getMac() != null && deviceEnum.getMac().equals(bleDevice.getMac())) {
                        connectionPwBle(bleDevice);
                    }
                }

                @Override
                public void onScanFinished(List<BleDevice> scanResultList) {

                }
            });
        } else {
            ToastUtils.showShort("设备已连接，请等待测量结果");
            showProgressDialog("等待接收体温数据");
        }
    }

    private void connectionPwBle(BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");
                showProgressDialog("正在连接体温设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
//                connectionPwBle(bleDevice);
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                fastBleDevice = bleDevice;
                showProgressDialog("等待接收体温数据");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getIndicate(bleDevice);
                    }
                },400);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
                disconnectDevice();
                cancelProgressDialog();
            }
        });
    }

    private void getIndicate(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE.toString(),
                UUID_NOTIFY.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        Log.e(TAG, "onCharacteristicChanged: "+ data );
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                        update(hexString);

                    }
                });
    }

    @Override
    public void update(String hexString) {
        try {
            Log.e(TAG, "update: " + hexString );
            if (hexString.length() > 18) {
                String temp = hexString.substring(12, 16);

                Log.e(TAG, "onCharacteristicChanged: " + temp );
                int tempi = Integer.parseInt(temp, 16);
                double tempd = tempi / 100.0;

                DecimalFormat df = new DecimalFormat("#.0");
                double roundedTempd = Double.parseDouble(df.format(tempd));

                Log.e(TAG, "onCharacteristicChanged: "  + roundedTempd );

                tv_state.setText("获取测量结果成功");
                tv_result.setText("温度值：" + roundedTempd + "℃");
                DeviceShowSaveData.getDataShow(roundedTempd + "", TwjConstans.DEVICE_NAME);
                // 存体温
                DeviceShowSaveData.saveTiwen1(roundedTempd + "");
                cancelProgressDialog();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void disconnectDevice() {
        try {
            cancelProgressDialog();
            fastBleDevice = null;
            BleManager.getInstance().disconnectAllDevice();
            BleManager.getInstance().destroy();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
